package com.zhen.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zhen.User.Result;
import com.zhen.Utils.JwtUtils;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class Interceptor implements HandlerInterceptor {
    @Autowired
    private Result result;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        // 自定义的请求头也要添加
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Tenant-Id, Blade-Auth, Content-Type, Authorization, credential, X-XSRF-TOKEN, token, username, client");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String url=request.getRequestURI().toString();
        System.out.println("url:"+url);
        String jwt = request.getHeader("token");
        System.out.println("jwt:"+jwt);
//        String jwt="zd29yZCI6IjEyMyIsIm5hbWUiOiIxMjMiLCJleHAiOjE3MTg4MTgwNzR9.a12TRZvkBin61fnCV07ddDSjpwCYlrqBm5fUAP71s3A";
//        if(!StringUtils.hasLength(jwt)){
        if(jwt==null||jwt.equals("")){
//            请求头为空
            System.out.println("为空");
            Result err =result.error();
            String notlogin=JSONObject.toJSONString(err);
            response.getWriter().print(notlogin);//响应给浏览器
            return false;
        }

        try {
            //解析令牌
            JwtUtils.jietoken(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            //解析jwt失败
            Result err =result.error();
            String notlogin= JSONObject.toJSONString(err);
            response.getWriter().write(notlogin);//响应给浏览器
            return false;
        }
        //令牌合法
        return true;
    }
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("后");
//    }
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("渲染完毕");
//        return;
//    }
}
